package com.netty.LongConnect;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;


/**
 * @author: sun.hongliang
 * @create: 2019/02/22 20:02
 */
public class Client {
    private int port;
    private String host;
    private SocketChannel socketChannel;

    public Client(int port, String host) {
        this.port = port;
        this.host = host;
    }

    public void start() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
                Bootstrap bootstrap = new Bootstrap();
                bootstrap.channel(NioSocketChannel.class)
                        .option(ChannelOption.SO_KEEPALIVE, true)
                        .option(ChannelOption.TCP_NODELAY, true)
                        .group(eventLoopGroup).remoteAddress(host, port)
                        .handler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            protected void initChannel(SocketChannel ch) throws Exception {
                                ch.pipeline().addLast(
                                        new LineBasedFrameDecoder(1024),
                                        new StringDecoder(),
                                        new MessageDecoder(),
                                        new MessageEncoder(),
                                        new ClientHandler());
                            }
                        });
                ChannelFuture future;
                try {
                    future = bootstrap.connect(host, port).sync();
                    if (future.isSuccess()) {
                        socketChannel = (SocketChannel) future.channel();
                        System.out.println("客户端连接成功...");
                    } else {
                        System.out.println("客户端开启失败...");
                    }
                    future.channel().closeFuture().sync();
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    eventLoopGroup.shutdownGracefully();
                }
            }
        }).start();
    }

    public void sendMessage(Object msg) {
        if (socketChannel != null) {
            socketChannel.writeAndFlush(msg);
        }
    }
}
